package gam.t1.triggers;

import gam.t1.conf.TextConfig;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.TextColor;
import org.bukkit.Color;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public final class URLTrigger extends BaseTrigger{
    private static TextComponent load;
    public URLTrigger() {
        setSync(TextConfig.sync);
    }
    @Override
    public Component runTrigger(Component component, String argument) {
        return component.clickEvent(ClickEvent.openUrl(argument));
    }

    @Override
    public Runnable nextSync(Component component, String argument) {
        if (load == null){
            load = Component.empty();
        }
        return () -> {
            try {
                int counts = 0;
                load.color(TextColor.color(Color.GRAY.asRGB())).content("loading...");
                component.hoverEvent(HoverEvent.showText(load));
                URL url1 = new URL(argument);
                while (counts < 3){
                    HttpURLConnection uC = (HttpURLConnection) url1.openConnection();
                    if (uC.getResponseCode() == 200){
                        load.color(TextColor.color(Color.GREEN.asRGB())).content("URL can be used.");
                        System.out.println("url useful");
                        break;
                    }
                    counts++;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                loger.warning("错误的URL格式");
            } catch (IOException e) {
                e.printStackTrace();
                loger.warning("Something warning in URL.");
            }
        };
    }


}
